

port_UsrUart=112
port_UsrUartConfig=101
port_Handshake=102
port_AddressChange=103
port_IdentitySwitch=104
port_AddressAllocator=105


function printPkg(pkg)	
	body = ""
	for i=1,#pkg do			
		body= body..string.format("%02X ", pkg[i])
	end
	print("recv %d data %04X->%d: %q",#pkg,pkg.addr, pkg.port,body)
end
	

function Handshake(target)
	pkg={string.byte('H'),1,2,3,4}
	pkg.addr = target
	pkg.port = port_Handshake
	send(pkg)
	pkg = recv(1000);	
	if(pkg == nil) then		
		print("Handshake fail")
		return 
	end	
	if(pkg[1] ~= string.byte('h')) then		
		print("Handshake fail, recv bad pkg")
		return 
	end	
	print("Handshake to %04X done!",pkg.addr)
end

function LedShow(target)
	pkg={string.byte('L')}
	pkg.addr = target
	pkg.port = port_Handshake
	send(pkg)
end


function GetVersion(target)
	pkg={string.byte('V')}
	pkg.addr = target
	pkg.port = port_Handshake
	send(pkg)
	pkg = recv(1000);	
	if(pkg == nil) then		
		print("GetVersion fail")
		return 
	end	
	if(pkg[1] ~= string.byte('v')) then		
		print("GetVersion fail, recv bad cmd %x", pkg[1] )
		return 
	end	
	if(#pkg ~= 5) then		
		print("GetVersion fail, recv bad len %d",#pkg)
		return 
	end	
	print("Version of %04X is %d.%d",pkg.addr, pkg[2]+pkg[3]*256,pkg[4]+pkg[5]*256)
end

function testRecv()
	pkg = recv(10);
	if(pkg~=nil)	then
		body = ""
		for i=1,#pkg do			
			body= body..string.format("%02X ", pkg[i])
		end
		print("recv %d data %04X->%d: %q",#pkg,pkg.addr, pkg.port,body)
		else
		print("recv nothing")
	end
end

